package learn_concurrent._9;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// Tow phase termination 两阶段终止模式
public class T16 {
	public static void main(String[] args) throws InterruptedException {
		Monitor monitor1 = new Monitor();
		monitor1.startMonitor();
		
		Monitor monitor2 = new Monitor();
		monitor2.startMonitor();
		Thread.sleep(3500);
		monitor1.stopMonitor();
		Thread.sleep(5000);
		monitor1.startMonitor();
	}
}

class Monitor {
	private final static Logger logger = LoggerFactory.getLogger(Monitor.class);

	private Thread thread;
	private volatile boolean stop = false;
	private volatile static boolean starting = false;

	private void doWork() {
		logger.debug("执行监控工作");
	}

	private void doAfterWork() {
		logger.debug("执行善后工作");
	}

	public void startMonitor() {
		synchronized (Monitor.class) {
			if (starting) {
				return;
			}
			starting = true;
		}
		thread = new Thread(() -> {
			while (true) {
				if (stop) {
					doAfterWork();
					starting = false;
					stop = false;
					break;
				}
				try {
					Thread.sleep(1000);
					doWork();
				} catch (InterruptedException e) {
				}
			}
		});
		thread.start();
	}

	public void stopMonitor() {
		stop = true;
		thread.interrupt();
	}
}
